<template>
    <div class="m_right">
        <p></p>
        <div class="mem_tit">订单列表</div>
        <form class="horizontal-form">
            <div class="form-item">
                <label>订单号：</label>
                <input type="text" name="serialNumber" v-model="serialNumber" />
            </div>

            <div class="form-item" v-if="filterUserId === ''">
                <label>登录账户：</label>
                <input type="text" name="loginName" v-model="loginName" />
            </div>
            <div class="form-item">
                <label>创建时间：</label>
                <input type="text" name="createTime" v-model="createTime" />
            </div>
            <div class="form-item">
                <label>订单状态：</label>
                <select name="state" v-model="state">
                    <option value='5'>全部</option>
                    <option value="0">未付款</option>
                    <option value="1">已付款</option>
                    <option value="2">已取消</option>
                    <option value="3">已完成</option>
                    <option value="4">已退款</option>
                </select>
            </div>
            <div class="form-item">
                <input type="button" value="查询" @click="getOrderList(1, 2)" />
                <input type="button" value="重置" @click="resetForm()" />
            </div>
        </form>
        <div class="order-wrapper" v-for="order in orderList" :key="order.id">

            <div class="order-info">
                <span style="color: #ff4e00;">订单号：{{ order.serialNumber }}</span>
                <span>用户名：{{ order.loginName }}</span>
                <span>地址：{{ order.userAddress }}</span>
                <span>创建时间：{{ order.createTime }}</span>
            </div>
            <table class="order-table">
                <thead>
                    <tr>
                        <th>商品名称</th>
                        <th>商品图片</th>
                        <th>商品数量</th>
                        <th>商品价格</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="orderDetail in order.orderDetialList" :key="orderDetail.id">
                        <td>{{ orderDetail.productName }}</td>
                        <td><img :src="'http://192.168.144.183:9090/easybuyImages/' + orderDetail.productImg"
                                width="50px"></td>
                        <td>{{ orderDetail.quantity }}</td>
                        <td style="color: #ff4e00;">￥{{ orderDetail.productPrice }}</td>
                    </tr>
                </tbody>
            </table>
            <div class="order-footer">
                <span style="color: #ff4e00;">订单金额：￥{{ order.cost }}</span>
                <span>订单状态：{{ ['未付款', '已付款', '已取消', '已完成', '已退款'][order.state] }}</span>
                <span v-if="order.state == 0"><a href="#" @click.once="toCancel(order.id)">取消订单</a></span>
                <span v-if="order.state == 1"><a href="#" @click.once="toRefund(order.id, order.payBy)">申请退款</a></span>
                <span v-if="order.state == 0 && filterUserId !== ''"><button class="pay-btn"
                        @click="openChannelDialog(order.id)">去支付</button></span>
                <span style="color: #ff4e00;" v-if="order.state == 0">剩余支付时间：{{ order.countdownText || '计算中...'
                }}</span>
                <span v-if="order.state != 0"><a href="#" @click.once="toDel(order.id)">删除订单</a></span>
            </div>
        </div>
        <div class="order-wrapper" v-if="pageInfo.total === 0">
            <span style="color: #ff4e00;">暂无订单哦！亲</span>
        </div>
        <!-- 分页条 -->
        <div class="pagination" v-if="pageInfo.pages > 0">
            <button :disabled="pageInfo.pageNum === 1" @click="turn(pageInfo.pageNum - 1)">上一页</button>

            <span v-for="p in showPages" :key="p" :class="{ active: p === pageInfo.pageNum }" @click="turn(p)">{{ p
                }}</span>

            <button :disabled="pageInfo.pageNum === pageInfo.pages" @click="turn(pageInfo.pageNum + 1)">下一页</button>
        </div>
        <!-- 支付通道选择弹窗 -->
        <el-dialog title="请选择支付方式" :visible.sync="payDialogVisible" width="320px" center :close-on-click-modal="false">
            <div style="text-align:center;">
                <el-button type="success" icon="el-icon-check" @click="choosePay('wx')">微信支付</el-button>
                <el-button type="primary" icon="el-icon-check" @click="choosePay('zfb')">支付宝支付</el-button>
            </div>
        </el-dialog>

        <!-- 微信支付二维码弹窗 -->
        <el-dialog title="微信扫码支付" :visible.sync="wxQrcodeVisible" width="260px" center @close="wxQrcode = ''">
            <div style="text-align:center">
                <qrcode-vue :value="wxQrcode" :size="200" level="H" />
                <p style="margin-top:10px;color:#999;">请使用微信扫一扫完成支付</p>
            </div>
            <div><button @click="flush()">完成支付</button></div>
        </el-dialog>
    </div>

</template>

<script>
import QrcodeVue from 'qrcode.vue'
export default {
    name: 'MemberOrderListRight',
    components: { QrcodeVue },
    data() {
        return {
            // 当前登录用户相关信息
            userId: '',
            filterUserId: '',

            // 分页信息
            pageInfo: {},
            orderList: [],
            // 查询条件
            serialNumber: '',
            loginName: '',
            createTime: '',
            state: 5,

            //支付相关信息
            payDialogVisible: false,   // 通道选择窗
            wxQrcodeVisible: false,    // 微信二维码窗
            wxQrcode: '',              // 微信二维码内容
            currentOrderId: ''         // 当前要支付的订单 id
        }
    },
    computed: {
        // 只显示 5 个页码，当前页尽量居中
        showPages() {
            const { pageNum, pages } = this.pageInfo;
            let start = Math.max(pageNum - 2, 1);
            let end = Math.min(start + 4, pages);
            if (end - start < 4) start = Math.max(end - 4, 1);
            const arr = [];
            for (let i = start; i <= end; i++) arr.push(i);
            return arr;
        }
    },
    methods: {

        // 解析路由并设置 filterUserId
        setFilter() {
            // 只要是“self”就强制只查自己
            if (this.$route.query.scope === 'self') {
                this.filterUserId = this.userId
            } else {
                this.filterUserId = ''   // all 或后台入口，可查看全部
            }
        },
        // 统一翻页方法
        turn(page) {
            if (page < 1 || page > this.pageInfo.pages) return;
            this.getOrderList(page, this.pageInfo.pageSize);
        },
        getOrderList(pageNum, pageSize) {
            const params = {
                pageNum: pageNum,
                pageSize: pageSize,
                serialNumber: this.serialNumber,
                loginName: this.loginName,
                createTime: this.createTime,
                userId: this.filterUserId
            }

            if (this.state === "0" || this.state === "1" || this.state === "2" || this.state === "3" || this.state === "4") {
                params.state = this.state
            }

            this.$axios({
                url: '/selectOrderByPage',
                method: 'post',
                data: params
            }).then(rs => {
                console.log(rs)
                if (rs.data.code === 5200) {
                    this.pageInfo = rs.data.pageInfo
                    this.orderList = rs.data.pageInfo.list
                }
                this.clearAllTimers(); // 先清掉旧的
                this.orderList.forEach(order => {
                    if (order.state === 0) {
                        this.startCountdown(order);
                    }
                });
            })
        },
        resetForm() {
            this.serialNumber = ''
            this.loginName = ''
            this.createTime = ''
            this.state = 4
            this.getOrderList(1, 2)
        },
        /* 1. 打开通道选择窗，并记录订单 id */
        openChannelDialog(orderId) {
            this.currentOrderId = orderId
            this.payDialogVisible = true
        },

        /* 2. 用户选了支付通道 */
        choosePay(channel) {
            this.payDialogVisible = false
            if (channel === 'zfb') {
                this.toZfbPay(this.currentOrderId)   // 走原来支付宝逻辑
            } else {
                this.toWxPay(this.currentOrderId)    // 走微信逻辑
            }
        }
        , toZfbPay(id) {
            this.$axios.get(`/ali/payByZfb/${id}`).then(rs => {
                console.log("支付信息" + rs)
                this.handlegotoPay(rs.data)
            })
        },
        toWxPay(id) {
            this.$axios.get(`/ali/payByWX/${id}`).then(rs => {
                const payUrl = rs.data.pay_url;
                if (payUrl) {
                    this.wxQrcode = payUrl;        // 设置二维码内容
                    this.wxQrcodeVisible = true;   // 打开弹窗
                } else {
                    this.$message.error('获取微信支付二维码失败');
                }
            })
        }
        ,
        flush() {
            this.wxQrcodeVisible = false
            this.getOrderList(1, 2)
        }
        ,
        handlegotoPay(data) {
            const formHtml = data;
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = formHtml;
            document.body.appendChild(tempDiv);

            const payForm = tempDiv.querySelector('form[name="punchout_form"]');
            if (!payForm) {
                document.body.removeChild(tempDiv); // 清理DOM
                throw new Error("支付表单不存在，无法发起支付");
            }

            payForm.submit();

            setTimeout(() => {
                if (document.body.contains(tempDiv)) {
                    document.body.removeChild(tempDiv);
                }
            }, 1000);
        }
        , toRefund(id, payBy) {
            if (payBy === 1) {
                alert("微信支付，当前无法退款！")
                return
            }
            const flag = confirm('确定要申请退款吗？');
            if (!flag) return;
            this.$axios.get(`/ali/refundByZfb/${id}`).then(rs => {
                this.handleRefundReceipt(rs.data);
                this.getOrderList(1, 2)
            })
        }
        , handleRefundReceipt(html) {
            // 0. 如果之前已经插过，先清掉
            const oldBox = document.getElementById('refundReceiptBox');
            if (oldBox) document.body.removeChild(oldBox);

            // 1. 新建一个容器，随便起个 id，方便后面删
            const box = document.createElement('div');
            box.id = 'refundReceiptBox';
            box.innerHTML = html;

            // 3. 插入页面
            document.body.appendChild(box);

            // 4. 点“遮罩”或“返回”按钮时关闭（后端返回的 HTML 里自带返回链接，这里再给个点击遮罩关闭）
            box.onclick = e => {
                // 如果点的是遮罩（不是内容区）就关闭
                if (e.target === box) {
                    document.body.removeChild(box);
                }
            };

            // 5. 自动滚动到顶部
            window.scrollTo({ top: 0, behavior: 'smooth' });
        },
        toDel(id) {
            const flag = confirm('确定要删除订单吗？');
            if (!flag) return;
            this.$axios({
                url: '/delOrder',
                params: {
                    id: id
                },
                method: 'get',
            }).then(rs => {
                if (rs.data.code === 5200) {
                    this.getOrderList(1, 2)
                } else {
                    alert("删除订单失败！")
                    this.getOrderList(1, 2)
                }
            })
        }
        , toCancel(id) {
            const flag = confirm('确定要取消订单吗？');
            if (!flag) return;
            this.$axios({
                url: '/cancelOrder',
                params: {
                    id: id
                },
                method: 'get'
            }).then(rs => {
                if (rs.data.code === 5200) {
                    this.getOrderList(1, 2)
                } else {
                    alert("取消订单失败！")
                    this.getOrderList(1, 2)
                }
            }
            )
        },
        // 计算剩余时间（单位：秒）
        getRemainingSeconds(createTime) {
            const created = new Date(createTime).getTime();
            const deadline = created + 15 * 60 * 1000; // 15分钟后
            const now = Date.now();
            return Math.max(0, Math.floor((deadline - now) / 1000));
        },

        // 格式化秒数为 mm:ss
        formatCountdown(seconds) {
            const m = String(Math.floor(seconds / 60)).padStart(2, '0');
            const s = String(seconds % 60).padStart(2, '0');
            return `${m}分${s}秒`;
        },

        // 启动倒计时
        startCountdown(order) {
            const timerKey = order.id;
            const update = () => {
                const remaining = this.getRemainingSeconds(order.createTime);
                this.$set(order, 'countdownText', this.formatCountdown(remaining));
                if (remaining <= 0) {
                    clearInterval(this.countdownTimers[timerKey]);
                    this.$set(order, 'countdownText', '支付已超时');
                }
            };
            update(); // 立即执行一次
            this.countdownTimers[timerKey] = setInterval(update, 1000);
        },

        // 清除所有定时器（防止内存泄漏）
        clearAllTimers() {
            if (!this.countdownTimers) {
                this.countdownTimers = {};
                return;
            }
            Object.values(this.countdownTimers).forEach(clearInterval);
            this.countdownTimers = {};
        }
    },
    mounted() {
        this.userId = window.sessionStorage.getItem('userId')
        //console.log("当前登录用户id", this.userId)
        this.setFilter()
        //console.log("当前查询用户id", this.filterUserId)
        this.getOrderList(1, 2)
    },
    watch: {
        // 同一组件复用时重新解析
        '$route.query.scope'() {
            this.setFilter()
            this.getOrderList(1, 2)
        }
    }

}
</script>

<style scoped>
/* 水平表单 */
.horizontal-form {
    margin-left: 5%;
    width: 90%;
    display: flex;
    align-items: center;
    /* 垂直居中 */
    gap: 12px;
    /* 列间距 */
    flex-wrap: wrap;
    /* 小屏自动换行 */
}

.form-item {
    display: flex;
    align-items: center;
    gap: 4px;
    /* label 与 input 间距 */
}

/* —— 订单相关：宽度 85% 并居中 —— */
.order-wrapper {
    width: 85%;
    margin: 20px auto;
    /* 居中 */
}

.order-info,
.order-footer {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
}

.order-table {
    width: 100%;
    border-collapse: collapse;
    margin: 10px 0;
}

.order-table th,
.order-table td {
    padding: 8px;
    text-align: center;
    border: 1px solid #e0e0e0;
}

.order-table th {
    background: #fafafa;
    font-weight: bold;
}

/* —— 订单相关：宽度 85% 并居中 —— */
.order-wrapper {
    width: 85%;
    margin: 20px auto;
    /* 居中 */
    border: 1px solid #dcdfe6;
    /* 新增：外边框 */
    border-radius: 4px;
    /* 可选：圆角更美观 */
    padding: 15px;
    /* 可选：让边框与内容留点空隙 */

}

.order-info,
.order-footer {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
}

.order-table {
    width: 100%;
    border-collapse: collapse;
    margin: 10px 0;
}

.order-table th,
.order-table td {
    padding: 8px;
    text-align: center;
    border: 1px solid #e0e0e0;
}

.order-table th {
    background: #fafafa;
    font-weight: bold;
}

/* 支付按钮样式 */
.pay-btn {
    background-color: #ff4e00;
    color: white;
    border: none;
    padding: 5px 10px;
    border-radius: 3px;
    cursor: pointer;
}

.pay-btn:hover {
    background-color: #e64600;
}

/* ---------- 分页条 ---------- */
.pagination {
    width: 85%;
    margin: 20px auto;
    display: flex;
    gap: 8px;
    font-size: 14px;
}

.pagination button {
    border: 1px solid #dcdfe6;
    background: #fff;
    color: #606266;
    padding: 4px 10px;
    border-radius: 3px;
    cursor: pointer;
}

.pagination button:disabled {
    opacity: .4;
    cursor: not-allowed;
}

.pagination span {
    border: 1px solid #dcdfe6;
    padding: 4px 8px;
    cursor: pointer;
}

.pagination span.active {
    background: #ff4e00;
    color: #fff;
    border-color: #ff4e00;
}
</style>